from flask import Blueprint, render_template, request, jsonify, session
import os
import  time
from utils.database_util import query_data

article_publish = Blueprint('article_publish', __name__)

@article_publish.route('/uedit',methods=['GET','POST'])
def uedit():
    param = request.args.get('action')
    if request.method == 'GET' and param == 'config':
        return render_template('config.json')

    elif request.method == 'POST' and request.agrs.get('action') == 'uploadimage':
        f = request.files['upfile']
        filename = f.filename

        suffix = filename.split('.')[-1]
        newname = time.strftime('%Y%m%d_%H%M%S_' + suffix)
        f.save('./resource/upload/' + newname)

        source = dest = './resource/upload/' + newname
        # compress_image(source, dest, width=1200)

        result = {}
        result['state'] = 'SUCCESS'
        result['url'] = "/upload/{filename}"
        result['title'] = filename
        result['original'] = filename
        return jsonify(result)
    elif request.method == 'GET' and param == 'listimage':
        list = []
        filelist = os.listdir('./resource/upload')

        for filename in filelist:
            if filename.lower().endswith('.png') or filename.lower().endswith('.jpg'):
                list.append({'uri': '/upload/%s' % filename})

        result = {}
        result['state'] = 'SUCCESS'
        result['list'] = list
        result['start'] = 0
        result['total'] = 50
        return jsonify(result)
@article_publish.route('/add_article', methods=['GET','POST'])
def add_article():
    userid = session.get('userid')
    if userid is None:
        return  "error"
    headline = request.form.get('headline')
    content = request.form.get('content')
    type = int(request.form.get('type'))
    credit = int(request.form.get('credit'))
    sql = "INSERT INTO `article`(`userid`,`type`,`headline`,`content`,`credit`) values (%d, %d, '%s', '%s', %d)" % (userid, type, headline, content, credit)
    print(sql)
    result = query_data(sql)
    return  "OK"

@article_publish.route('/a_publish/')


def publish():
    return render_template('article_publish.html')
